package com.longcai.cm.api.listener;

import cn.hutool.core.thread.ThreadUtil;
import com.longcai.cm.delay.SecKillGoodDelay;
import com.longcai.cm.domain.JaGoodsInfo;
import com.longcai.cm.service.JaGoodsInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.DelayQueue;

/**
 * @author libingxing
 */
@Component
@Order(10)
public class DelayConsumer implements InitializingBean {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private DelayQueue<SecKillGoodDelay> secKillGoodDelayQueue;

    @Resource
    private JaGoodsInfoService goodsInfoService;

    @Override
    public void afterPropertiesSet() {
        ThreadUtil.execAsync(() ->
                {
                    while (true) {
                        try {
                            final SecKillGoodDelay task = secKillGoodDelayQueue.take();
                            final String goodId = task.getGoodId();
                            logger.info("秒杀商品：" + goodId + "进入定时操作");
                            goodsInfoService.lambdaUpdate()
                                    .eq(JaGoodsInfo::getId, goodId)
                                    .set(JaGoodsInfo::getStatus, 0)
                                    .update();
                        } catch (Exception e) {
                            e.printStackTrace();
                            logger.info("秒杀商品延时任务异常跳过" + e.getMessage());
                        }
                    }
                }
        );
    }
}
